package com.lhcai.lc.category.designsimulate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 3242. 设计相邻元素求和服务
 *
 * @author liuhuaicai
 * @since 2024-10-28 22:19
 */
public class NeighborSum {
    public static void main(String[] args) {
        NeighborSum neighborSum = new NeighborSum(new int[][]{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
        System.out.println(neighborSum.adjacentSum(1));
        System.out.println(neighborSum.adjacentSum(4));
        System.out.println(neighborSum.diagonalSum(4));
        System.out.println(neighborSum.diagonalSum(8));

    }

    Map<Integer, List<Integer>> adjacentMap;
    Map<Integer, List<Integer>> diagonalMap;

    int row;
    int col;

    public NeighborSum(int[][] grid) {
        row = grid.length;
        col = grid[0].length;

        adjacentMap = new HashMap<>();
        diagonalMap = new HashMap<>();


        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                getAdjacent(grid, i, j);
                getDiagonalMap(grid, i, j);

            }
        }
    }


    public int adjacentSum(int value) {
        List<Integer> list = adjacentMap.get(value);
        int sum = 0;
        for (Integer integer : list) {
            sum += integer;
        }
        return sum;
    }

    public int diagonalSum(int value) {
        List<Integer> list = diagonalMap.get(value);
        int sum = 0;
        for (Integer integer : list) {
            sum += integer;
        }
        return sum;
    }

    private void getDiagonalMap(int[][] grid, int i, int j) {
        List<Integer> diagonalList = new ArrayList<>();
        if (i - 1 >= 0 && j - 1 >= 0) {
            diagonalList.add(grid[i - 1][j - 1]);
        }
        if (i - 1 >= 0 && j + 1 < col) {
            diagonalList.add(grid[i - 1][j + 1]);
        }
        if (i + 1 < row && j - 1 >= 0) {
            diagonalList.add(grid[i + 1][j - 1]);
        }
        if (i + 1 < row && j + 1 < col) {
            diagonalList.add(grid[i + 1][j + 1]);
        }
        diagonalMap.put(grid[i][j], diagonalList);
    }

    private void getAdjacent(int[][] grid, int i, int j) {
        List<Integer> adjacentList = new ArrayList<>();
        if (i - 1 >= 0) {
            adjacentList.add(grid[i - 1][j]);
        }
        if (i + 1 < row) {
            adjacentList.add(grid[i + 1][j]);
        }
        if (j - 1 >= 0) {
            adjacentList.add(grid[i][j - 1]);
        }
        if (j + 1 < col) {
            adjacentList.add(grid[i][j + 1]);
        }
        adjacentMap.put(grid[i][j], adjacentList);
    }
}
